import {defineStore} from 'pinia'
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'


interface State {
  token: string|undefined
  name: string
  avatar:string|''
  userId: number | null
}
interface UserInfo {
  username: string
  password:string
}

export const useUserStore =defineStore('auth/user',  {
  // 转换为函数
  state: (): State => ({
    token:getToken(),
    avatar:'',
    name: '',
    userId: null,
  }),
  getters:{
  },
  actions:{
    async login(userInfo:UserInfo){
      const { username, password } = userInfo
      const { data } = await login({ username: username.trim(), password: password })
      //commit('SET_TOKEN', data.token)
      setToken(data.token)
    },
    async getInfo(state:State){
      const { name, avatar } = await getInfo(state.token)
      // commit('SET_NAME', name)
      // commit('SET_AVATAR', avatar)
      this.updateUser({name,avatar})
    },
    async logout(){

      //await logout(this.getToken())
      //commit('SET_TOKEN', '')
      removeToken()
    },
    async loadUser(id: string) {
      if (this.userId !== null) throw new Error('Already logged in')
      const res = await getInfo(id)
      this.updateUser(res)
    },
    updateUser(payload:State) {
      this.name = payload.name
      this.avatar = payload.avatar
      this.userId = payload.userId
    },
    resetToken(){

    },
    clearUser() {
      this.$reset()
    },
  }
})
